<template>
  <div class="articleList">
    <van-pull-refresh v-model="isPullLoading"
     @refresh="onRefresh"
     :success-text="pullRefreshText"
     :success-duration="1500">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <ArticleItem v-for="item in list" :key="item.art_id+''"
         :articleItem="item"/>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleList } from '@/api/article.js'
import { Toast } from 'vant'
import ArticleItem from '@/components/articleitem.vue'
export default {
  props: {
    channelId: {
      type: Number,
      require: true
    }
  },
  data () {
    return {
      list: [],
      loading: false, // 是否在加载中
      finished: false, // 数据是否已经全部加载完成
      preTimestamp: Date.now(), // 时间戳
      error: false,
      isPullLoading: false,
      pullRefreshText: ''
    }
  },

  created () {

  },

  methods: {
    async onLoad () {
      try {
        // 发送请求 获取数据
        const res = await getArticleList({
          channel_id: this.channelId,
          timestamp: this.preTimestamp,
          with_top: 1
        })
        if (Math.random() > 0.5) {
          console.lg('123')
        }
        // 保存数据
        this.list.push(...res.results)
        this.preTimestamp = res.pre_timestamp
        // 加载状态结束
        this.loading = false
        // 数据全部加载完成
        if (!this.preTimestamp) {
          this.finished = true
        }
      } catch (err) {
        Toast.clear()
        this.loading = false
        this.error = true
      }
    },
    async onRefresh () {
      try {
        const res = await getArticleList({
          channel_id: this.channelId,
          timestamp: Date.now(),
          with_top: 1
        })
        if (Math.random() > 0.5) {
          console.lg('123')
        }
        console.log(res)
        this.isPullLoading = false
        this.list.unshift(...res.results)
        this.pullRefreshText = '共刷新' + res.results.length + '条数据'
      } catch (err) {
        this.isPullLoading = false
        this.pullRefreshText = '网络异常，稍后重试'
      }
    }
  },
  components: {
    ArticleItem
  }
}
</script>

<style scoped lang="less">
.articleList{
  // padding-bottom: 100px;
  height: 80vh;
  overflow-y: scroll;
}
</style>
